<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules" label-position="top">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="formData.username" :disabled="isRoot" placeholder="请输入账号" clearable/>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="formData.nickname" placeholder="请输入昵称" clearable />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model.trim="formData.password" show-password clearable placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="passwordConfirm">
                    <el-input v-model.trim="formData.passwordConfirm" show-password clearable placeholder="请输入确认密码"/>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="formData.mobile" placeholder="请输入手机号" clearable />
                </el-form-item>
                <el-form-item label="是否禁用" prop="isDisable">
                    <el-radio-group v-model="formData.isDisable" placeholder="是否禁用">
                        <el-radio
                            v-for="(item, index) in dictData.is_disable"
                            :key="index"
                            :label="item.value"
                            :disabled="!item.status"
                        >
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
<!--                    <el-switch v-model="formData.isDisable" :active-value="1" :inactive-value="0" />-->
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { adminAdd, adminEdit, adminDetail } from '@/api/perms/admin'
import { useDictOptions } from '@/hooks/useDictOptions'
import { roleAll } from '@/api/perms/role'
import { postAll } from '@/api/org/post'
import { deptLists } from '@/api/org/department'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑书记员' : '新增书记员'
})

const formData = reactive({
    id: '',
    username: '',
    nickname: '',
    password: '',
    passwordConfirm: '',
    isDisable: '0',
    roleIds: ['2'],
    mobile: ''
})

// const isRoot = computed(() => {
//     return formData.id == 1
// })

const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}
const formRules = reactive({
    username: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    nickname: [
        {
            required: true,
            message: '请输入昵称',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ] as any[],
    passwordConfirm: [
        {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[],
    mobile: [
        {
            required: true,
            message: '请输入手机号',
            trigger: ['blur']
        }
    ],
})

const { optionsData } = useDictOptions<{
    role: any[]
    post: any[]
    dept: any[]
}>({
    role: {
        api: roleAll
    },
    post: {
        api: postAll
    },
    dept: {
        api: deptLists
    }
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await adminEdit(formData) : await adminAdd(formData)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (row: any) => {
    formRules.password = []
    formRules.passwordConfirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    const data = await adminDetail({
        id: row.id
    })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData
})
</script>
